<?php

namespace App\Http\Controllers\Commit;

use App\Http\Controllers\Controller as BaseController;
use App\Repository\Commit\RoleRepository;
use App\Repository\MenuRepository;
use App\Repository\SystemRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * @OA\Tag(
 *     name="后台菜单模块",
 *     description="菜单模块",
 * )
 */
class MenuController extends BaseController
{
    private $repoist;
    private $system;
    private $role;

    public function __construct(MenuRepository $MenuRepository, SystemRepository $SystemRepository, RoleRepository $RoleRepository)
    {
        $this->repoist = $MenuRepository;
        $this->system = $SystemRepository;
        $this->role = $RoleRepository;
    }

    /**
     * @OA\Post(
     *     path="/api/v1/menu",
     *     tags={"后台菜单模块"},
     *     summary="添加",
     * @OA\Parameter(name="token", in="header", @OA\Schema(type="string")),
     *     @OA\Parameter(name="menu_tag", in="query", @OA\Schema(type="菜单名称 必填")),
     *     @OA\Parameter(name="path", in="query", @OA\Schema(type="路径 必填")),
     *     @OA\Parameter(name="parent_id", in="query", @OA\Schema(type="父级id 默认0 顶级菜单")),
     *     @OA\Parameter(name="grandfather", in="query", @OA\Schema(type="爷爷级id 默认 0")),
     *     @OA\Parameter(name="order_no", in="query", @OA\Schema(type="显示顺序")),
     *     @OA\Parameter(name="icon", in="query", @OA\Schema(type="图标")),
     *     @OA\Parameter(name="type", in="query", @OA\Schema(type="0 菜单 1动作 2报表菜单")),
     *     @OA\Parameter(name="hasFlag", in="query", @OA\Schema(type="是否显示 0 不显示 1 显示")),
     *     @OA\Parameter(name="window", in="query", @OA\Schema(type="窗口属性 默认 _self")),
     *     @OA\Parameter(name="action_tag", in="query", @OA\Schema(type="动作标识")),
     *     @OA\Parameter(name="action_menuid", in="query", @OA\Schema(type="属于某个菜单")),
     *     @OA\Response(response=200, description="  {code: int, info:string, data:[token=>1]}"
     *     )
     * )
     */
    public function store(Request $request)
    {
        $menuType = strtoupper($request->get('menuType'));
        $perms = '';
        if (empty($request->get('perms')) && $request->has('path')) {
            if ($menuType === 'F' || $menuType === 'C') {
                $perms = str_replace('/', ':', $request->get('path'));
                $request->offsetSet('perms', $perms);
            }
        }
        switch ($menuType) {
            case 'M':
                if (empty($request->get('component'))) {
                    $request->offsetSet('component', 'Layout');
                }
                break;
            case 'F':
            case 'C':
                if (!$request->has('backPath') || empty($request->get('backPath'))) {
                    return $this->returnMsg(1, '请传递路由方式参数');
                }
                break;
        }
        if (!empty($request->get('path'))) {
            $request->offsetSet('back_query', $request->get('path'));
        }
//        这个用来做请求方法的字段，旧字段不改了
        $request->offsetSet('back_path', $request->get('backPath'));
        $request->offsetSet('menu_name', $request->get('menuName'));
        $request->offsetSet('menu_type', $request->get('menuType'));
        $request->offsetSet('order_num', $request->get('orderNum'));
        $request->offsetSet('is_frame', $request->get('isFrame'));
        $request->offsetSet('is_cache', $request->get('isCache'));
        $request->offsetSet('parent_id', $request->get('parentId'));

        return $this->repoist->add($request);
    }

    public function index(Request $request)
    {
        $where = [];
        if (!empty($request->get('status'))) {
            $where['where']['status'] = $request->get('status');
        }
        if (!empty($request->get('menuName'))) {
            $where['like'] = ['menu_name' => $request->get('menuName')];
        }
        if (!empty($request->get('perms'))) {
            $where['where'] = ['perms' => $request->get('perms')];
        }
        if (!empty($request->get('backQuery'))) {
            $where['where'] = ['back_query' => $request->get('backQuery')];
        }
        // var_dump($where,1111111111);
        $data = $this->repoist->index($where);
        return $data;
    }
    /**
     * @OA\put(
     *     path="/api/v1/menu",
     *     tags={"后台菜单模块"},
     *     summary="菜单修改",
     *    @OA\Parameter(name="token", in="header", @OA\Schema(type="string")),
     *     @OA\Parameter(name="id", in="query", @OA\Schema(type="id")),
     *     @OA\Parameter(name="menu_tag", in="query", @OA\Schema(type="菜单名称")),
     *     @OA\Parameter(name="path", in="query", @OA\Schema(type="路径")),
     *     @OA\Parameter(name="parentId", in="query", @OA\Schema(type="父级id 默认0 顶级菜单")),
     *     @OA\Parameter(name="grandfather", in="query", @OA\Schema(type="爷爷级id 默认 0")),
     *     @OA\Parameter(name="order_no", in="query", @OA\Schema(type="显示顺序")),
     *     @OA\Parameter(name="icon", in="query", @OA\Schema(type="图标")),
     *     @OA\Parameter(name="type", in="query", @OA\Schema(type="0 菜单 1动作 2报表菜单")),
     *     @OA\Parameter(name="hasFlag", in="query", @OA\Schema(type="是否显示 0 不显示 1 显示")),
     *     @OA\Parameter(name="window", in="query", @OA\Schema(type="窗口属性 默认 _self")),
     *     @OA\Parameter(name="action_tag", in="query", @OA\Schema(type="动作标识")),
     *     @OA\Parameter(name="action_menuid", in="query", @OA\Schema(type="属于某个菜单")),
     *     @OA\Response(response=200, description="  {code: int, info:string, data:[token=>1]}"
     *     )
     * )
     */
    /**
     * 修改数据
     * 修改条件 id
     */
    public function save(Request $request)
    {
        if (!$request->get('menuId')) {
            return $this->returnMsg(1, '请传递id参数');
        }
        $menuType = strtoupper($request->get('menuType'));
        $perms = '';
        if (empty($request->get('perms')) && $request->has('path')) {
            if ($menuType == 'F' || $menuType == 'C') {
                $perms = str_replace('/', ':', $request->get('path'));
                $request->offsetSet('perms', $perms);
            }
        }
        if (!empty($request->get('path'))) {
            $request->offsetSet('back_query', $request->get('path'));
        }
        switch ($menuType) {
            case 'M':
                if (empty($request->get('component'))) {
                    $request->offsetSet('component', 'Layout');
                }
                break;
            case 'F':
            case 'C':
                if (!$request->has('backPath') || empty($request->get('backPath'))) {
                    return $this->returnMsg(1, '请传递路由方式参数');
                }
                break;
        }
//        这个用来做请求方法的字段，旧字段不改了
        $request->offsetSet('back_path', $request->get('backPath'));
        $where = ['menu_id' => $request->get('menuId')];
        $request->offsetSet('menu_name', $request->get('menuName'));
        $request->offsetSet('menu_type', $request->get('menuType'));
        $request->offsetSet('order_num', $request->get('orderNum'));
        $request->offsetSet('is_frame', $request->get('isFrame'));
        $request->offsetSet('is_cache', $request->get('isCache'));
        $request->offsetSet('parent_id', $request->get('parentId'));
        return $this->repoist->edit($where, $request);
    }
    /**
     * @OA\Get(
     *     path="/api/v1/menu/id",
     *     tags={"后台菜单模块"},
     *     summary="单条数据显示",
     *     @OA\Parameter(name="token", in="header", @OA\Schema(type="string")),
     *     @OA\Response(response=200, description="  {code: int, msg:string, data:[token=>1]}  "
     *     )
     * )
     */
    /**
     * 查询单条数据
     *
     * @param Request $id
     */
    public function show($id)
    {
        $where = ['menu_id' => $id];
        //查询一条数据
        $return = $this->repoist->getOne($where);
        if (!empty($return)) {
            if (isset($return['is_frame'])) {
                $return['is_frame'] = (string)$return['is_frame'];
            }
            if (isset($return['is_cache'])) {
                $return['is_cache'] = (string)$return['is_cache'];
            }
            $return = usfirstArr($return);
        }
        return $this->returnMsg(200, '查询成功', $return);
    }

    /**
     * @OA\Get(
     *     path="/api/v1/menu",
     *     tags={"后台菜单模块"},
     *     summary="列表",
     *      @OA\Parameter(name="token", in="header", @OA\Schema(type="string")),
     *      @OA\Parameter(name="name", in="query", @OA\Schema(type="string")),
     *     @OA\Response(response=200, description="  {code: int, msg:string, data:[token=>1]}  "
     *     )
     * )
     */

    public function listss(Request $request)
    {
        $where = [];
        if (!empty($request->get('name'))) {
            $where['where'] = ['menu_tag' => $request->get('name')];
        }

        $return = $this->repoist->lists($where);
        return $return;
    }
    /**
     * @OA\delete(
     *     path="/api/v1/menu/id",
     *     tags={"后台菜单模块"},
     *     summary="菜单删除",
     *     @OA\Parameter(name="token", in="header", @OA\Schema(type="string")),
     *     @OA\Response(response=200, description="  {code: int, msg:string, data:[token=>1]}  "
     *     )
     * )
     */
    /**
     * 删除数据
     */

    public function destroy($id)
    {
        if (!$id) {
            return $this->returnMsg(1, '请传递参数');
        }
        $where = [
            'menu_id' => $id
        ];
        return $this->repoist->del($where);
    }

    /**
     * @OA\Get(
     *     path="/api/v1/menuList",
     *     tags={"后台菜单模块"},
     *     summary="菜单",
     *      @OA\Parameter(name="token", in="header", @OA\Schema(type="string")),
     *     @OA\Response(response=200, description="  {code: int, msg:string, data:[token=>1]}  "
     *     )
     * )
     */
    public function menuList(Request $request)
    {
        $where = [
            'menu_action' => 'menu',
            'parent_id' => 0,
            'hasFlag' => 1,
        ];
        $role_id = !empty($request->get('user')->role_id) ? $request->get('user')->role_id : 0;
        // var_dump($request->get('user')->role_id,55555555555);
        $data = [
            'homeInfo' => [
                'title' => '欢迎',
                'href' => 'welcome.html',
            ],
            'logoInfo' => [
                'image' => $this->system->getOneVal(['name' => 'backstage_home_log']),
                'title' => $this->system->getOneVal(['name' => 'backstage_home_title']),
            ],
            'menuInfo' => [
                'title' => '常规管理',
                'target' => '_self',
                'icon' => '',
                'href' => '',
                'child' => $this->repoist->sel($where, $role_id)
            ],
        ];
        return $this->returnMsg(200, '查询成功', $data);
    }

    public function getRouters(Request $request)
    {
        $where = [
            // 'menu_action' => 'menu',
            'parent_id' => 0,
            'status' => 0
            // 'hasFlag' => 1,
        ];
        $role_id = !empty($request->user->role_id) ? $request->user->role_id : '';
        $deptId = $request->user->dept_id;
        // $role_id = 0;
        if (!empty($deptId)) {
            $wheres = [
                'dept_id' => $request->user->dept_id,
                // 'dept_id' => 14,
                'shop_id' => $request->user->shop_id,
                'status' => 0
            ];
            $res = DB::table('dept')->where($wheres)->first();
            if (!$res) {
                return $this->returnMsg(100, '未查询到您的权限');
            }
            $role_id = $res->role_id;
            if (strpos($role_id, ',') !== false) {
                $role_id = explode(',', $role_id);
            }
        }
        if (empty($role_id)) {
            return $this->returnMsg(101, '您没有后台权限');
        }
        $res = $this->repoist->sel($where, $role_id);
        return $this->returnMsg(200, '查询成功', $res);
    }
    /**
     * @OA\Get(
     *     path="/api/v1/menuTree",
     *     tags={"后台菜单模块"},
     *     summary="菜单树结构",
     *      @OA\Parameter(name="token", in="header", @OA\Schema(type="string")),
     *     @OA\Response(response=200, description="  {code: int, msg:string, data:[token=>1]}  "
     *     )
     * )
     */
    //权限设置 菜单
    public function menuTree(Request $request)
    {
        if (empty($request->user->role_id)) {
            return [];
        }
        $where = [
            'id' => !empty($request->user->role_id) ? $request->user->role_id : 2,
        ];
        $role = $this->role->getOne($where);
        if (empty($role)) {
            return [];
        }
        $menuArr = $this->repoist->getSel();
        // var_dump($menuArr, 1111111111);
        $menu = [];
        if (!empty($role['in_ids'])) {
            $menu = explode(',', trim($role['in_ids'], ','));
        }
        $menuList = $this->handleTree($menuArr, $menu);
        return $menuList;
    }

    //过滤是否是可以打开的状态
    public function handleTree($menu, $role)
    {
        $menuList = [];
        if (!empty($menu)) {
            foreach ($menu as $key => $v) {
                $isSpread = false;
                $isChecked = false;
                $menuList[$key]['title'] = $v['title'];
                $menuList[$key]['id'] = $v['id'];
                $menuList[$key]['href'] = '';
                if (in_array($v['id'], $role)) {
                    $isChecked = true;
                    $isSpread = true;
                }
                $menuList[$key]['checked'] = $isChecked;
                $menuList[$key]['spread'] = $isSpread;
                if (!empty($v['child'])) {
                    $menuList[$key]['children'] = $this->handleTree($v['child'], $role);
                }
            }
        }
        return $menuList;
    }

    /**
     * @OA\Get(
     *     path="/api/v1/getOneMenuTree",
     *     tags={"后台菜单模块"},
     *     summary="一级菜单树",
     *      @OA\Parameter(name="token", in="header", @OA\Schema(type="string")),
     *     @OA\Response(response=200, description="  {code: int, msg:string, data:[token=>1]}  "
     *     )
     * )
     */
    public function OneMenuTree()
    {
        $data = $this->repoist->getOneTrue();
        $str = array();
        if (!empty($data)) {
            foreach ($data as $key => $v) {
                if (!empty($v['child'])) {
                    $str[] = $v['id'];
                }
            }
        }
        return $this->returnMsg(200, '查询成功', $str);
    }

    //菜单树
    public function getTree(Request $request)
    {

        $role_id = $request->user->role_id;
        if (empty($role_id)) {
            $wheres = [
                'dept_id' => $request->user->dept_id,
            ];
            $res = DB::table('dept')->where($wheres)->first();
            if (!$res) {
                return $this->returnMsg(100, '未查询到您的权限');
            }
            $role_id = $res->role_id;
        }

        $data = $this->repoist->getOneTrue([], [], 0, 5, $role_id);
        return $this->returnMsg(200, '查询成功', $data);
    }

    /**
     * @OA\get(
     *     path="/api/v1/clearCash",
     *     tags={"后台菜单模块"},
     *     summary="清除缓存",
     *     @OA\Response(response=200, description="  {code: int, info:string, data:[token=>1]}"
     *     )
     * )
     */
    public function clearCash()
    {
        $this->repoist->clearCache();
        return $this->returnMsg(200, '清除成功');
    }
}
